<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class LogicClassStudentController extends BaseController {

	public function index() {
		if(IS_POST) {
			$logicClassId  = I('post.logic_class_id');
		} else {
			$logicClass = M('LogicClass')->find();
			$logicClassId = $logicClass['id'];
		}
		$map['logic_class_id'] = $logicClassId;
		$logicClassStudents = M('LogicClassStudent')->where($map)->select();
		$student_ids = array();
		foreach ($logicClassStudents as $logicClassStudent) {
			array_push($student_ids, $logicClassStudent['student_id']);
		}
		$map = array();
		$map['id'] = array('in', $student_ids);
		$student_ids && $students = D('Student')->where($map)->relation('class')->order('id')->select();
		$this->assign('logic_classes', M('LogicClass')->select());
		$this->assign('logic_class_id', $logicClassId);
		$this->assign('students', $students);
		$this->display();
	}

	public function add() {
		$academies = D('Academy')->relation('majors')->select();
		$this->assign('academies', $academies);
		$this->assign('logic_classes', M('LogicClass')->select());
		$this->display();
	}

	public function addPost() {
		if(!IS_POST) {
			$this->redirect('LogicClassStudent/index');
		}
		$logicClassStudent = D('LogicClassStudent');
		if(!$logicClassStudent->create()) {
			$this->error($logicClassStudent->getError());
		}
		if(!$logicClassStudent->checkUnique($logicClassStudent->data())) {
			$this->error('已存在！');
		}
		if(!$logicClassStudent->add()) {
			$this->error('数据写入失败！');
		}
		$this->success('添加成功！', U('LogicClassStudent/index'), 0);
	}

	public function deletePost() {
		if(!IS_POST) {
			$this->redirect('LogicClassStudent/index');
		}
		$logicClassId = I('post.logic_class_id');
		$studentId = I('post.student_id');

		// 删除前先删除相关的学生作业表记录
		$homeworkIds = M('Homework')
			->where(array('logic_class_id' => $logicClassId))
			->getField('id', true);
		$homeworkIds && $homeworkStudents = M('HomeworkStudent')
			->where(array('student_id' => $studentId))
			->where(array('homework_id' => array('in', $homeworkIds)))
			->select();
		foreach($homeworkStudents as $row) {
			$filename = $row['file_savepath'] . $row['file_savename'];
			unlink($filename);
		}
		$homeworkIds && $result = M('HomeworkStudent')
			->where(array('student_id' => $studentId))
			->where(array('homework_id' => array('in', $homeworkIds)))
			->delete();
		if(false === $result) {
			$this->error('删除相关的学生作业表记录失败！');
		}
		// 删除逻辑班级学生表记录
		$map['logic_class_id'] = $logicClassId;
		$map['student_id'] = $studentId;
		if(!M('LogicClassStudent')->where($map)->delete()) {
			$this->error('删除失败！');
		}
		$this->success('删除成功！');
	}

	public function getStudentsByClass() {
		$map['major_id'] = I('major_id');
		$map['grade'] = I('grade');
		$map['class'] = I('class');
		$class = M('Class')->where($map)->find();
		$students = M('Student')->where(array('class_id' => $class['id']))->order('id')->select();
		$this->ajaxReturn($students);
	}

}
